import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:go_router/go_router.dart';
import 'package:leader_doctor_flutter/common/data/app.dart';
import 'package:leader_doctor_flutter/common/http/api.dart';
import 'package:leader_doctor_flutter/common/http/http_client.dart';
import 'package:leader_doctor_flutter/common/http/url_helper.dart';
import 'package:leader_doctor_flutter/common/utils/date_utils.dart';
import 'package:leader_doctor_flutter/common/utils/image_utils.dart';
import 'package:leader_doctor_flutter/common/utils/string_utils.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/model/bank_card.dart';
import 'package:leader_doctor_flutter/router/router.dart';
import 'package:leader_doctor_flutter/styles/colors.dart';
import 'package:leader_doctor_flutter/ui/wallet/model/my_wallet_model.dart';
import '../../../common/utils/toast_utils.dart';
import '../model/new_order.dart';

/// @Author lixiaobin
/// @Date 2024/1/26
/// @Description 我的钱包主界面
class WalletMainPage extends StatefulWidget {
  const WalletMainPage({super.key});

  @override
  State<WalletMainPage> createState() => _WalletMainPageState();
}

class _WalletMainPageState extends State<WalletMainPage> {
  WalletOrder? _walletOrder;
  MyWalletModel? _myWalletModel;
  var _switchSelected = false;

  /// 银行卡状态：1:正常；2:待绑定；3:待更换；
  int? _bankCardBindStatus = -1;

  @override
  void initState() {
    super.initState();

    _myWalletInfo();
    _getWalletStatus();
    _bankCardStatus();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        appBar: AppBar(
            toolbarHeight: 0,
            shadowColor: Colors.transparent,
            backgroundColor: Colors.transparent,
            systemOverlayStyle: const SystemUiOverlayStyle(
              systemNavigationBarColor: Color(0xFF000000),
              systemNavigationBarIconBrightness: Brightness.light,
              statusBarIconBrightness: Brightness.light,
              statusBarBrightness: Brightness.dark,
            )),
        backgroundColor: ColorRes.colorf5f7f9,
        body: Container(
            height: double.infinity,
            child: Stack(children: [
              Container(color: ColorRes.white, height: 300.w, width: double.infinity),
              SizedBox(
                height: 178.w,
                child: ImageLoader.loadAsset('icon_wallet_bg.webp', double.infinity, fit: BoxFit.fill),
              ),
              SizedBox(height: 50.w),
              Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                const TitleBarWidget(),
                SizedBox(height: 25.w),
                _buildDataBoard(),
                SizedBox(height: 10.w),
                Container(
                  color: ColorRes.white,
                  child: Column(
                    children: [
                      GestureDetector(
                          behavior: HitTestBehavior.opaque,
                          onTap: () {
                            if (_bankCardBindStatus == -1) {
                              return;
                            }
                            context.push(PageUrl.bankCardManage).then((value) {
                              _myWalletInfo();
                              _bankCardStatus();
                            });
                          },
                          child: Container(
                              height: 56.w,
                              alignment: Alignment.centerLeft,
                              padding: EdgeInsets.symmetric(horizontal: 16.w),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '银行卡管理',
                                    style: TextStyle(color: ColorRes.color333333, fontSize: 15.sp),
                                  ),
                                  Row(
                                    children: [
                                      Text(
                                        _getBindStatusStr(),
                                        style: TextStyle(color: ColorRes.colorMain, fontSize: 15.sp),
                                      ),
                                      SizedBox(width: 6.w),
                                      ImageLoader.loadAsset('icon_white_arrow.webp', 0,
                                          color: ColorRes.color333333, size: Size(8.w, 15.w))
                                    ],
                                  )
                                ],
                              ))),
                      CommWidget.buildLine(margin: EdgeInsets.symmetric(horizontal: 16.w)),
                      Container(
                          height: 56.w,
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.symmetric(horizontal: 16.w),
                          child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                            Text(
                              '钱包锁',
                              style:
                                  TextStyle(color: ColorRes.color333333, fontSize: 15.sp, fontWeight: FontWeight.w500),
                            ),
                            Transform.scale(
                                scale: 0.7,
                                child: SizedBox(
                                    width: 26.w,
                                    height: 26.w,
                                    child: CupertinoSwitch(
                                        activeColor: ColorRes.colorMain,
                                        value: _switchSelected,
                                        onChanged: (value) {
                                          String tipStr =
                                              value ? '开启钱包锁后进去我的钱包将校验钱包锁密码，确认开启吗？' : '关闭钱包锁后进去我的钱包将不校验钱包锁密码，确认关闭吗？';
                                          _buildOpenLockDialog(tipStr, value);
                                        })))
                          ])),
                    ],
                  ),
                ),
                CommWidget.buildLine(height: 10.w, color: ColorRes.colorf5f7f9),
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.w),
                  decoration: const BoxDecoration(color: ColorRes.white),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '最近收入',
                        style: TextStyle(color: ColorRes.color333333, fontSize: 15.sp, fontWeight: FontWeight.w500),
                      ),
                      SizedBox(height: 20.w),
                      Column(
                        children: _walletOrder?.newOrder?.map((e) => _buildIncomeItem(e)).toList() ?? [],
                      ),
                      Visibility(
                          visible: (_walletOrder?.newOrder?.length ?? 0) == 0,
                          child: Container(
                              width: double.infinity,
                              height: 180.w,
                              alignment: Alignment.center,
                              child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
                                ImageLoader.loadAsset('icon_wallet_empty.webp', 140.w),
                              ])))
                    ],
                  ),
                ),
              ]),
              Positioned(
                  bottom: 20.w,
                  left: 0.w,
                  right: 0.w,
                  child: Container(
                    margin: EdgeInsets.symmetric(horizontal: 29.w),
                    child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                      Text(
                        '温馨提示：',
                        style: TextStyle(color: ColorRes.color333333, fontSize: 14.sp, fontWeight: FontWeight.w500),
                      ),
                      Text(
                        '1.诊疗待结算金额为医生在本平台所有收入（含平台服务费+税)。\n2.诊疗待结算金额3天(72小时)后可提现，展示在待提现金额，每次提现不低于100.00元。',
                        style: TextStyle(fontSize: 12.sp, color: ColorRes.color666666, height: 1.5),
                        maxLines: 5,
                      ),
                    ]),
                  ))
            ])));
  }

  /// 收入明细 item
  Widget _buildIncomeItem(NewOrder? item) {
    return SizedBox(
        height: 65.w,
        child: Column(
          children: [
            Expanded(
                child: Row(
              children: [
                ClipRRect(
                    borderRadius: BorderRadius.circular(25.w),
                    child: ImageLoader.loadPatientAvatar(item?.icon, size: Size(45.w, 45.w))),
                SizedBox(width: 10.w),
                Expanded(
                    child: Column(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
                  Expanded(
                      child: Row(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                        Expanded(
                            child: Text(item?.sysOrder?.userName ?? '',
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(color: ColorRes.color333333, fontSize: 14.sp))),
                        Text(MyDateUtils.format(item?.payTime, 'yyyy.MM.dd HH:mm:ss'),
                            style: TextStyle(color: ColorRes.color666666, fontSize: 13.sp))
                      ])),
                  Expanded(
                      child: Row(
                          crossAxisAlignment: CrossAxisAlignment.end,
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                        SizedBox(
                            height: 20.w,
                            child: Row(
                              children: [
                                CommWidget.buildConsultTypeBtn(item?.sysOrder?.orderTypeVal ?? ''),
                                SizedBox(width: 10.w),
                                CommWidget.buildConsultTypeBtn('义诊', isShow: item?.promotionChannel == '4'),
                              ],
                            )),
                        Text('￥${StringUtils.formatNumber(item?.totalFee)}',
                            style: TextStyle(color: ColorRes.colorec6755, fontSize: 15.sp)),
                      ]))
                ])),
              ],
            )),
            SizedBox(height: 15.w),
          ],
        ));
  }

  /// 添加银行卡弹窗
  _buildAddBankDialog() {
    CommWidget.buildBottomSheetDialog(context,
        title: '温馨提示',
        buildView: (c) => Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('暂无可用的银行卡，建议您绑定银行卡后重试', style: TextStyle(color: ColorRes.color333333, fontSize: 16.sp)),
                SizedBox(
                  height: 40.w,
                ),
                Row(
                  children: [
                    Expanded(
                        child: CommWidget.buildLeftBtn('取消', () {
                      Navigator.of(c).pop();
                    })),
                    Container(width: 12.w),
                    Expanded(
                        child: CommWidget.buildRightBtn('去绑定', () {
                      Navigator.of(c).pop(1);
                    }))
                  ],
                ),
              ],
            )).then((value) {
      if (value == 1) {
        _loadWeb();
      }
    });
  }

  /// 钱包锁弹窗
  _buildOpenLockDialog(String tipStr, bool operate) {
    return CommWidget.buildBottomSheetDialog(context,
        title: '温馨提示',
        buildView: (c) => Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(tipStr, style: TextStyle(color: ColorRes.color333333, fontSize: 16.sp)),
                SizedBox(
                  height: 40.w,
                ),
                Row(
                  children: [
                    Expanded(
                        child: CommWidget.buildLeftBtn('取消', () {
                      Navigator.of(c).pop();
                    })),
                    Container(width: 12.w),
                    Expanded(
                        child: CommWidget.buildRightBtn('确定', () {
                      Navigator.of(c).pop(1);
                    }))
                  ],
                ),
              ],
            )).then((value) {
      if (value == 1) {
        _switchSelected = operate;
        _setWalletStatus();
        setState(() {});
      }
    });
  }

  /// 加载添加银行卡web页面
  _loadWeb() async {
    UrlHelper.loadH5Page('添加银行卡', '${UrlHelper.formatExecutorUrl(Api.bankCard)}&sourceType=1');
  }

  /// 我的钱包明细
  _myWalletInfo() async {
    var user = App.instance.userInfo;
    var response = await HttpClient.get(HttpRequest(Api.walletIndex, urlParams: {'doctorId': user?.id}));
    var result = ServiceResult<WalletOrder>(response, (map) => WalletOrder.fromJson(map));
    if (result.success) {
      _walletOrder = result.responseBody;
    }

    var httpRequest = await HttpClient.postJson(HttpRequest(Api.getYzhAccount, body: {'userId': user?.id}));
    var serviceResult = ServiceResult<MyWalletModel>(httpRequest, (map) => MyWalletModel.fromJson(map));
    if (serviceResult.success) {
      _myWalletModel = serviceResult.responseBody;
    }

    setState(() {});
  }

  /// 查询钱包锁状态
  _getWalletStatus() async {
    var user = App.instance.userInfo;
    var response = await HttpClient.postJson(HttpRequest(Api.queryMoneyBagLockStatus, body: {
      'userMedicalId': user?.id ?? '',
    }));
    var serviceResult = ServiceResult.simple(response);
    if (serviceResult.success) {
      _switchSelected = serviceResult.responseBody;
      setState(() {});
    }
  }

  /// 设置钱包锁状态
  _setWalletStatus() async {
    var user = App.instance.userInfo;
    var response = await HttpClient.postJson(HttpRequest(Api.setMoneyBagLockStatus, body: {
      'userMedicalId': user?.id ?? '',
      'isEnable': _switchSelected ? '1' : '0',
    }));
    var serviceResult = ServiceResult.simple(response);
    if (!serviceResult.success) {
      ToastUtils.toast(serviceResult);
      _switchSelected = !_switchSelected;
      setState(() {});
    }
  }

  /// 查询银行卡绑定状态
  _bankCardStatus() async {
    var user = App.instance.userInfo;
    var response =
        await HttpClient.post(HttpRequest(Api.bankCardStatus, urlParams: {'userId': user?.id}, isShowLoading: false));
    var serviceResult = ServiceResult<int?>.simple(response);
    if (serviceResult.success) {
      _bankCardBindStatus = serviceResult.responseBody;
    }
  }

  /// 提现
  _checkBindBank(Function function) async {
    var user = App.instance.userInfo;
    var response = await HttpClient.post(HttpRequest(Api.findBankCardByUserId, body: {'userId': user?.id}));
    var serviceResult = ServiceResult<List<BankCardModel>>.list(
        response, (list) => (list ?? []).map((e) => BankCardModel.fromJson(e)).toList());
    if (serviceResult.success) {
      if ((serviceResult.responseBody?.length ?? 0) > 0) {
        function.call();
      } else {
        _buildAddBankDialog();
      }
    } else {
      ToastUtils.toast(serviceResult);
    }
  }

  /// 银行卡绑定状态展示
  String _getBindStatusStr() {
    if (_bankCardBindStatus == 2) {
      return '待绑定';
    } else if (_bankCardBindStatus == 3) {
      return '待更换';
    }
    return '';
  }

  Widget _buildDataBoard() {
    return Card(
        elevation: 5.w,
        shadowColor: ColorRes.color173c80d1,
        shape: const RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(4.0))),
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        child: Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(vertical: 23.w, horizontal: 16.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '诊疗待结算金额(元)',
                    style: TextStyle(color: ColorRes.color666666, fontSize: 13.sp),
                  ),
                  SizedBox(height: 6.w),
                  Text(
                    '￥${StringUtils.formatNumber(_myWalletModel?.totalFee)}',
                    style: TextStyle(color: ColorRes.color333333, fontSize: 18.sp),
                  ),
                  SizedBox(height: 12.w),
                  GestureDetector(
                      onTap: () {
                        context.push(PageUrl.walletIncomeList);
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(vertical: 2.w, horizontal: 10.w),
                        decoration: BoxDecoration(borderRadius: BorderRadius.circular(10.w), color: ColorRes.colorMain),
                        child: Text(
                          '查看明细',
                          style: TextStyle(color: ColorRes.white, fontSize: 12.sp),
                        ),
                      ))
                ],
              ),
              Container(
                width: 1,
                height: 67,
                color: ColorRes.colorf5f5f5,
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '诊疗待提现金额(元)',
                    style: TextStyle(color: ColorRes.color666666, fontSize: 13.sp),
                  ),
                  SizedBox(height: 6.w),
                  Text(
                    '￥${StringUtils.formatNumber(_myWalletModel?.noWithdrawFee)}',
                    style: TextStyle(color: ColorRes.color333333, fontSize: 18.sp),
                  ),
                  SizedBox(height: 12.w),
                  Row(
                    children: [
                      GestureDetector(
                          onTap: () {
                            context.push(PageUrl.walletWithdrawalRecord);
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(vertical: 2.w, horizontal: 10.w),
                            decoration:
                                BoxDecoration(borderRadius: BorderRadius.circular(10.w), color: ColorRes.colorMain),
                            child: Text(
                              '提现记录',
                              style: TextStyle(color: ColorRes.white, fontSize: 12.sp),
                            ),
                          )),
                      SizedBox(width: 7.w),
                      GestureDetector(
                          onTap: () {
                            _checkBindBank(() {
                              context.push(PageUrl.walletReflect);
                            });
                          },
                          child: Container(
                            padding: EdgeInsets.symmetric(vertical: 2.w, horizontal: 10.w),
                            decoration:
                                BoxDecoration(borderRadius: BorderRadius.circular(10.w), color: ColorRes.color1ed1d4),
                            child: Text(
                              '提现',
                              style: TextStyle(color: ColorRes.white, fontSize: 12.sp),
                            ),
                          ))
                    ],
                  )
                ],
              )
            ],
          ),
        ));
  }
}

class TitleBarWidget extends StatelessWidget {
  const TitleBarWidget({
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
        margin: EdgeInsets.only(top: MediaQuery.of(context).padding.top),
        height: 50.w,
        width: double.infinity,
        child: Stack(
          children: [
            IconButton(
              icon: const Icon(Icons.arrow_back, color: ColorRes.white),
              onPressed: () async {
                FocusScope.of(context).unfocus();
                var canPop = context.canPop();
                if (canPop) {
                  context.pop();
                } else {
                  SystemNavigator.pop();
                }
              },
            ),
            Container(
                width: double.infinity,
                height: double.infinity,
                alignment: Alignment.center,
                child: Text(
                  ModalRoute.of(context)?.settings.name ?? '',
                  style: TextStyle(color: ColorRes.white, fontSize: 18.sp),
                )),
            Container(
                alignment: Alignment.centerRight,
                margin: EdgeInsets.only(right: 16.w),
                child: GestureDetector(
                    onTap: () {
                      UrlHelper.loadH5Page('结算规则', Api.walletRule);
                    },
                    child: ImageLoader.loadAsset('icon_wallet_alert.png', 16.w))),
          ],
        ));
  }
}
